var app = getApp();
var custId = app.globalData.custID;
var openId = "";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    beusedPay: false,
    orderId: "",
    orderMoney: '0.00',
    onlinePayMoney: '0.00',
    paymentList: [],
    payType: '',
    payName: '选择支付方式',
    payLog: '',
    popin: false,
    shows: 'display:none;',
    payNo: '',
    activityMoney: '',
    payTypeId: '',
  },
  changePopin: function () {
    this.setData({
      popin: !this.data.popin
    });
  },
  changePaytype: function (e) {
    var paylist = this.data.paymentList;
    for (var i = 0, len = paylist.length; i < len; i++) {
      if (paylist[i].PayTypeID == e.currentTarget.id) {
        paylist[i].checked = true;
      } else {
        paylist[i].checked = false;
      }
    }
    this.setData({
      payTypeId: e.currentTarget.id,
      payType: e.currentTarget.dataset.paytype,
      payName: e.currentTarget.dataset.payname,
      payLog: e.currentTarget.dataset.paylog,
      popin: false,
      shows: '',
      paymentList: paylist
    });    
  },
  //去支付
  gopay: function (e) {
    var payTypeId = this.data.payTypeId;
    var payType = this.data.payType;
    if (payTypeId == null || payTypeId == '') {
      wx.showModal({
        content: '请选择支付方式',
        showCancel: false,
        confirmText: "确定"
      })
      return;
    }
    var openid = wx.getStorageSync('openId');
    var that = this;
    if (that.data.clickNum == 0) {
      wx.showLoading({
        title: '提交中...',
        mask: true
      });
      that.setData({
        clickNum: 1
      })

      if (payType != 5) {
        wx.request({
          url: app.globalData.apiurl + '/mobile/api/OrderForm/SmallGoPay',
          data: { CustId: custId, PayNo: this.data.payNo, OpenId: openid, PayTypeId: payTypeId },
          method: 'GET',
          header: {
            'X_ManuName': app.globalData.manuName
          },
          success: function (res) {
            wx.hideLoading();
            if (res.data.code == 1200) {
              var jsonStr = JSON.parse(res.data.content);
              wx.requestPayment({
                'timeStamp': jsonStr.timeStamp,
                'nonceStr': jsonStr.nonceStr,
                'package': jsonStr.package,
                'signType': jsonStr.signType,
                'paySign': jsonStr.paySign,
                'success': function (res) {
                  callBack(that);
                },
                'fail': function (res) {
                  wx.redirectTo({
                    url: '/pages/unpaid/unpaid?OrderID=' + that.data.orderId
                  });
                },
                'complete': function (res) {
                  that.setData({
                    clickNum: 0
                  })

                }
              });
            } else {
              that.setData({
                clickNum: 0
              })
              wx.showModal({
                content: res.data.msg,
                showCancel: false,
                confirmText: "确定"
              })
            }
          },
          fail: function (res) {
            wx.hideLoading();
            that.setData({
              clickNum: 0
            })
          }
        });
      } else {
        //余额支付
        wx.request({
          url: app.globalData.apiurl + '/mobile/api/OrderForm/BlancePay',
          data: { CustId: custId, PayNo: that.data.payNo, UserId: wx.getStorageSync('UserInfo').UserID },
          method: 'GET',
          header: {
            'X_ManuName': app.globalData.manuName
          },
          success: function (res) {
            wx.hideLoading();
            if (res.data.code == 1) {
              //支付成功
              wx.showModal({
                content: '支付成功',
                showCancel: false,
                confirmText: "确定",
                success: function (res) {
                  if (res.confirm) {
                    wx.switchTab({
                      url: '/pages/myorders/myorders',
                    });
                  }
                }
              });
            } else {
              that.setData({
                clickNum: 0
              })
              wx.showModal({
                content: res.data.msg,
                showCancel: false,
                confirmText: "确定"
              });
            }
          },
          fail: function (res) {
            wx.hideLoading();
            that.setData({
              clickNum: 0
            });
          }
        });
      }

    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      orderId: options.OrderID,
      payNo: options.PayNo,
      clickNum: 0
    });
    //加载订单
    loadOrder(this);
    //加载支付方式
    loadPayment(this);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      clickNum: 0
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

//加载订单
function loadOrder(that) {
  wx.showLoading({
    title: '加载中...',
    mask: true
  });
  wx.request({
    url: app.globalData.apiurl + '/mobile/api/OrderForm/GetOrderForUnionPayWechat',
    data: { custId: custId, payNo: that.data.payNo },
    method: 'GET',
    header: {
      'X_ManuName': app.globalData.manuName
    },
    success: function (res) {
      wx.hideLoading();
      if (res.data.code == 1200) {
        var contentObj = res.data.content;

        var PointName = contentObj.PointName;  //积分名称
        var CommissionName = contentObj.CommissionName;  //佣金名称
        var UseMoney = parseFloat(contentObj.UseMoney);  //活动使用佣金
        var UseScore = parseFloat(contentObj.UsePoint);  //活动使用积分
        //获取活动已使用的积分，佣金
        var ActivityUseStr = "";
        if (UseMoney > 0)
          ActivityUseStr += "+" + UseMoney + CommissionName;
        if (UseScore > 0)
          ActivityUseStr += "+" + UseScore + PointName;

        that.setData({
          orderMoney: parseFloat(contentObj.OrderMoney),
          onlinePayMoney: parseFloat(contentObj.OrderMoney),
          activityMoney: ActivityUseStr
        });
      } else {
        wx.showModal({
          content: res.data.msg,
          showCancel: false,
          confirmText: "确定"
        })
      }
    }
  })
}

//加载支付方式
function loadPayment(that) {
  wx.request({
    url: app.globalData.apiurl + '/mobile/api/OrderForm/GetPayTypeListByTerminal',
    data: { custId: custId, useTerminal: 3 },
    header: {
      'X_ManuName': app.globalData.manuName
    },
    method: 'GET',
    success: function (res) {
      if (res.data.code == 1200) {
        var paylist = res.data.content;
        if (paylist != null && paylist.length > 0) {
          for (var i = 0, len = paylist.length; i < len; i++) {
            if (i == 0) {
              paylist[i].checked = true;
              that.setData({
                payTypeId: paylist[i].PayTypeID,
                payType: paylist[i].PayType,
                payName: paylist[i].PayName,
                payLog: paylist[i].PayLog,
              });
            } else {
              paylist[i].checked = false;
            }
          }          
        }
        that.setData({
          paymentList: paylist
        });
      } else {
        console.log('加载失败');
      }
    }
  })
}

//支付回调
function callBack(that) {
  wx.redirectTo({
    url: '/pages/paySucceed/paySucceed?Total_fee=' + that.data.onlinePayMoney
  });
  // wx.request({
  //   url: app.globalData.apiurl + '/mobile/api/OrderForm/SmallPayCompleteCallBack',
  //   data: { custId: custId, payNo: that.data.payNo },
  //   header: {
  //     'X_ManuName': app.globalData.manuName
  //   },
  //   method: 'GET',
  //   success: function (res) {
  //     if (res.data.code == 1200) {
  //       wx.redirectTo({
  //         url: '/pages/paySucceed/paySucceed?Total_fee=' + res.data.content
  //       });
  //     } else {
  //       wx.showModal({
  //         content: res.data.msg,
  //         showCancel: false,
  //         confirmText: "确定"
  //       })
  //     }
  //   }
  // })
}
